import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入

declare var $: any;
@Component({
	selector: 'sa-resource',
	templateUrl: './header-manage.component.html'
})
export class HeaderManageComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
            field: {
				validators: {
					notEmpty: {
						message: '请填写字段名称'
					}
				}
			},
			fieldName: {
				validators: {
					notEmpty: {
						message: '请填写字段标识'
					}
				}
			}
            // reasons: {
			// 	trigger:"change",
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请选择后台判断原因'
			// 		}
			// 	}
			// },
		}
	};
	tableData = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	btnData: any = [];
	resourceAdd: boolean = false;
	resourceEdit: boolean = false;
	resourceDeleteBatch: boolean = false;
	mark: string=''; //菜单名称
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	formType: string= 'new';
	headerFrom: any={
		field: '',
		fieldName: '',
		mark: '',
		menuName: '',
		remark: '',
		isEnable: 1,
		id: ''
	}
	isShared: boolean = true
	ngOnInit() {
		// this.initBtn();
		this.load();
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
            System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.initAllRepairPoint().then(()=>{ 
					this.initRepairPointSelect();
					this.initRepairPointSelect2();
				});
            })
        })
		System.import('script-loader!smartadmin-plugins/bower_components/jquery-nestable/jquery.nestable.js').then(()=> {})
	}
	//table刷新
	refresh() {
		this.load();
	}
	//初始化权限按钮
	initBtn() {
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:resource')));
		if(!this.btnData) {
			return
		};
		for(let item of this.btnData) {
			if(item.sourceKey === "resource:add" && item.parentId) {
				this.resourceAdd = true;
			}
			if(item.sourceKey === "resource:edit" && item.parentId) {
				this.resourceEdit = true;
			}
			if(item.sourceKey === "resource:deleteBatch" && item.parentId) {
				this.resourceDeleteBatch = true;
			}
		}
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		var that = this;
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				mark: this.mark
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("header/queryHeaderPage.html", reqdata).subscribe(data => {
			for(var i=0;i<data.exhibitDatas.length;i++){
				// 停用启用
				if(data.exhibitDatas[i].isEnable == 1){
					data.exhibitDatas[i].isStatus = true;
				}else{
					data.exhibitDatas[i].isStatus = false
				}
			}

			System.import('assets/js/bootstrap-switch.min.js').then(
				()=>{System.import('assets/css/bootstrap-switch.min.css').then(()=>{
					setTimeout(function(){
						that.initSwitch();
						that.isSwitch = true
					},1)
					
				})
			});

			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//新建资源
	new_resource(modal) {
		modal.show();
		this.formType = 'new';
		this.headerFrom.field = '';
		this.headerFrom.fieldName = '';
		this.headerFrom.mark = '';
		this.headerFrom.menuName = '';
		this.headerFrom.remark = '';
		this.headerFrom.isEnable = 1;
		this.headerFrom.id = '';
		this.delRepairPoint2();
		$("#HeaderFrom").data('bootstrapValidator').resetForm();
	}
	//编辑资源页面
	updata_resource(row,modal) {
		modal.show();
		this.formType = 'updata';
		this.headerFrom.field = row.field;
		this.headerFrom.fieldName = row.fieldName;
		this.headerFrom.remark = row.remark;
		this.headerFrom.isEnable = row.isEnable;
		this.headerFrom.mark = row.mark;
		this.headerFrom.menuName =row.menuName;
		this.headerFrom.id = row.id
		this.isShared = row.isStatus;
		$("#menuName").val(row.menuName).change();
		var str=$("<span class='select2-selection__rendered'>"+row.menuName+"</span>");
		$("#select2-menuName-container").empty();
		$("#select2-menuName-container").attr("title",row.menuName);
		$("#select2-menuName-container").prepend(str);
	}
	del_resource(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("header/deletedHeaderById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success) {
					this.load();
				}
			})
		})
	}

	isSwitch:boolean = false; //默认隐藏

	//初始化开关
	initSwitch() {
		var that = this;
		$('.isStatus').bootstrapSwitch({    //初始化按钮
			onText:"开启",
			offText:"停用",
			onColor:"primary",
			offColor:"warning",
			onSwitchChange:function(event,state){
			   if(state==true){
					that.checkStatus('1',event.target.id,event.target.title);
				}else{
					that.checkStatus('0',event.target.id,event.target.title);
				}
			  }
		 });
	}
	//是否启用
	checkStatus(check,id,title) {
		var	dataSource = {
				id: id,
				isEnable: check,
				mark: title
			}
		this.jsonApiService.http_obj("header/batchActivation.html",dataSource).subscribe(data=> {
			if(data.success){
				this.load()
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}

	repairPointList:any = [];// 菜单名称
	// 删除菜单-查询
	delRepairPoint() {
	    this.mark = '';
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str=$("<span class='select2-selection__placeholder'>请选择</span>");
        $('#repairPointSelect2').val("");
        $("#select2-repairPointSelect2-container").empty();
        $("#select2-repairPointSelect2-container").attr("title","");
        $("#select2-repairPointSelect2-container").prepend(str);
	}
	delRepairPoint2() {
		this.headerFrom.mark = '';
		this.headerFrom.menuName ='';
        //采用简单粗暴的方法清除;官方推荐的方法失效
        var str=$("<span class='select2-selection__placeholder'>请选择</span>");
        $('#menuName').val("");
        $("#select2-menuName-container").empty();
        $("#select2-menuName-container").attr("title","");
        $("#select2-menuName-container").prepend(str);
	}
	// 菜单数据
    initAllRepairPoint() {
        var that = this;
        return new Promise(function (resolve, reject) {
            that.jsonApiService.http("header/queryMenuResource.html",null).subscribe(data=> {
                if(data.success){
                    var menuList = data.data;
                    var selectdata = [];
                    for(var i = 0 ; i < menuList.length ; i++) {
						if(menuList[i].parent != '#'){
							var obj = {
								id:menuList[i].id,
								text:menuList[i].text,
								mark:menuList[i].sourceKey
							}
							selectdata.push(obj);
						}
                    }
                }
                that.repairPointList = selectdata;
                resolve();
            })
        })
	}
	// 菜单配置
	initRepairPointSelect() {
	    let that = this;
	    // 菜单-查询条件
        $("#repairPointSelect2").select2({
            language : "zh-CN",
            placeholder :"请选择",
            allowClear : true,
            data: this.repairPointList
        }).on("select2:select", function (e){
            var data = e.params.data;
			that.mark = data.mark;
        });
	}
	initRepairPointSelect2() {
	    let that = this;
	    // 菜单-查询条件
        $("#menuName").select2({
            language : "zh-CN",
            placeholder :"请选择",
            allowClear : true,
            data: this.repairPointList
        }).on("select2:select", function (e){
            var data = e.params.data;
			that.headerFrom.mark = data.mark;
			that.headerFrom.menuName = data.text;
        });
	}

	isSharedChange(val){
		this.headerFrom.isEnable = val;
        if(val == "1"){
            this.isShared = false
        }else{
            this.isShared = true
        }
	}
	headerClose(modal){
		modal.hide();
	}
	headerSubmit(modal){
		$('#HeaderFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#HeaderFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			if(!this.headerFrom.menuName){
				this.jsonApiService.message('请选择菜单名称');
				return;
			}
			if(this.formType == 'updata'){
				this.jsonApiService.http_obj('header/updateHeaderById.html',this.headerFrom).subscribe(data=> {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.load();
						modal.hide();
					}
				})
			}else{
				var requdata = this.headerFrom;
				delete requdata.id;
				this.jsonApiService.http_obj('header/insertHeader.html',requdata).subscribe(data=> {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.load();
						modal.hide();
					}
				})
			}
			
		}
	}
}